<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.prototype.finally()</title>
</head>
<body>
    <h1>Promise.prototype.finally()</h1>
    <h2>不管Promise对象最后状态如何，都会执行的操作</h2>

    <script>
        // 基本用法
        Promise.resolve('成功')
            .finally(() => {
                console.log('finally执行');
            })
            .then(result => console.log(result));

        Promise.reject('失败')
            .finally(() => {
                console.log('finally执行');
            })
            .catch(error => console.log(error));

        // finally的实际应用：关闭服务
        function server() {
            const server = {
                running: true,
                close: function() {
                    this.running = false;
                    console.log('服务关闭');
                }
            };
            return server;
        }

        const s = server();
        Promise.resolve('操作')
            .then(result => {
                console.log(result);
                throw new Error('出错');
            })
            .catch(error => {
                console.log(error.message);
            })
            .finally(() => {
                s.close();
            });
    </script>
</body>
</html> 